//
//  ControllerViewController.m
//  微博2期
//
//  Created by J on 15/12/6.
//
//

#import "ComposeViewController.h"
#import "AccountTool.h"
#import "EmotionTextView.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "ComposeToolbar.h"
#import "CompostPhotosView.h"
#import "EmotionKeyboard.h"
#import "Emotion.h"//表情
@interface ComposeViewController ()<UITextViewDelegate,ComposeToolbarDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,weak) EmotionTextView * textView;//输入控件textView
@property(nonatomic,weak) ComposeToolbar * toolBar;//键盘顶部的工具条
@property(nonatomic,weak) CompostPhotosView * photosView;//存放拍照或者从相册中选择的图片
@property(nonatomic,strong) EmotionKeyboard * emotionKeyboard;//自定义表情键盘  strong 为了不被释放
@property(nonatomic,assign)BOOL switchingKeyboard;
@end

@implementation ComposeViewController
#pragma mark --懒加载
-(EmotionKeyboard *)emotionKeyboard{
    
    if (!_emotionKeyboard) {
        EmotionKeyboard * emotionKeyboar = [[EmotionKeyboard alloc]init];
        emotionKeyboar.width = self.view.width;//键盘宽度 系统会强制键盘宽度为屏幕宽度  前提是键盘本来就有非0的宽度
        emotionKeyboar.height = 216;
        self.emotionKeyboard = emotionKeyboar;
    }
    
    return _emotionKeyboard;
}


#pragma mark --系统方法
- (void)viewDidLoad {
    [super viewDidLoad];

    
//    self.automaticallyAdjustsScrollViewInsets = NO;//自动调增scrollViewInset 当scrollView 遇到NavigationBar UITabBar ToolBar Tabbar的情况下 不论是否被导航栏挡住 都会内缩63
    [self setupNav];//设置导航栏内容
    
    [self setupTextView];//添加输入控件
//    NSLog(@"%s",__FUNCTION__);
    
    //添加工具条
    [self setupToolbar];
    
    
    //添加相册
    [self setupPhotosView];
}

/**
 *      添加相册
 */
- (void)setupPhotosView{
    CompostPhotosView * photosView =[[CompostPhotosView alloc]init];
//    photosView.backgroundColor = RamdomColor;
    photosView.y = 100;
    photosView.width = self.view.width;
    photosView.height = self.view.height;//高度随意
    [self.textView addSubview:photosView];
    self.photosView = photosView;

}


/**
 *      添加工具条
 */
- (void)setupToolbar{
    ComposeToolbar * toolbar = [[ComposeToolbar alloc]init];
    toolbar.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"compose_toolbar_background"]];//平铺
    toolbar.width = self.view.width;
    toolbar.height = 44;
    toolbar.y = self.view.height - toolbar.height;
    toolbar.x = 0;
    toolbar.delegate = self;
    self.toolBar = toolbar;

    //设置显示在键盘顶部的内容
//    self.textView.inputAccessoryView = toolbar;
    [self.view addSubview:toolbar];
    //设置键盘
//    self.textView.inputView = [UIButton buttonWithType:UIButtonTypeContactAdd];
 
}
#pragma mark --UIToolbarDelegate


- (void)compostToolbar:(ComposeToolbar *)toolBar didClickButtton:(ComposeToolbarDelegateButtonType)buttonType{
    
    [self.textView becomeFirstResponder];
    switch (buttonType) {
        case ComposeToolbarDelegateButtonCamera://拍照
        {
            [self openCamera];
//            NSLog(@"拍照");
            
        }
            break;
        case ComposeToolbarDelegateButtonPicture://相册
        {
            [self openAlbum];

//            NSLog(@"相册");

        }
            break;
        case ComposeToolbarDelegateButtonMention://@
        {
//            NSLog(@"@");

        }
            break;
        case ComposeToolbarDelegateButtonTrend://#
        {
            NSLog(@"#");

        }
            break;
        case ComposeToolbarDelegateButtonEmotion://表情
        {
//            NSLog(@"表情");
            [self switchKeyboard];
        }
            break;
            
        default:
            break;
    }
    
}




/** 
 切换键盘
 */
- (void)switchKeyboard{
    
    //开始切换键盘
    
//    [self.view endEditing:YES];
//    [self.textView endEditing:YES];

    if (!self.textView.inputView) {//切换为自定义表情键盘
        
        self.textView.inputView = self.emotionKeyboard;
        self.toolBar.showEmotionButton = NO;//不显示键盘按钮
//        self.toolBar.y= 216;

    }else{//切换为系统自定义键盘
        self.textView.inputView = nil;//为空就切换为系统自带键盘
        self.toolBar.showEmotionButton = YES;//显示键盘按钮
//        self.toolBar.y= 216-37;
        }
    self.switchingKeyboard = YES;
    [self.textView endEditing:YES];
    //结束切换键盘
    self.switchingKeyboard = NO;
    [self.textView resignFirstResponder];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.textView becomeFirstResponder];
        //结束切换
    });

    

}

#pragma mark --其它方法
- (void)openCamera{
    
    [self openImagePickerController:UIImagePickerControllerSourceTypeCamera];
}


- (void)openAlbum{
    //如果想自己写一个图片选择器 得利用AssetLibrary.framework 利用这个框架可以获得手机上所有相册图片
    
    [self openImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
}



- (void)openImagePickerController:(UIImagePickerControllerSourceType)type{
    
    if (![UIImagePickerController isSourceTypeAvailable:type]) return;//如果不能用返回
    UIImagePickerController * ipc = [[UIImagePickerController alloc]init];
    ipc.sourceType = type;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];

    
}

#pragma mark --UIImagePickerControllerDelegate
/** 从UIImagePickerController 选择完图片后调用(拍照完毕活着选择相册图片完毕)
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //info中就包含了选择的图片
//    NSLog(@"%@",info);
    //添加图片到photosView中
    UIImage * image = info[UIImagePickerControllerOriginalImage];
    [self.photosView addPhoto:image];
    [picker dismissViewControllerAnimated:YES completion:nil];//选完图片控制器还在所以需要dismiss

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{//点击了取消按钮
    
    [picker dismissViewControllerAnimated:YES completion:nil];//选完图片控制器还在所以需要dismiss


}

- (void)dealloc{
    
    
    [NoficationCenter removeObserver:self];//移除通知
}

/**
 UITextField
 1.文字永远是一行, 不能显示多行文字
 2.有placeholder属性设置占位文字
 3.继承于UIControl  可以通过 - (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents; 监听
 4.监听一些行为
 1>设置代理
 2>addTarget:action:forEvent:
 3>通知  UITextFieldTextDidEndEditingNotification
 
 UITextView:
 1.能显示任意行文字
 2.不能设置占位文字
 3.继承于 UIScrollView 内容超出了可以滚动
 4.设置代理
 5.通知 UITextViewTextDidEndEditingNotification
 
 */


- (UITextView *)textView{
    
    if (!_textView) {
        
        EmotionTextView * textView = [[EmotionTextView alloc]init];
        textView.delegate = self;
        textView.placeHolder = @"分享你的新鲜事...";
//        textView.placeholderColor = [UIColor grayColor];
//        textView.height = 150;
//        textView.backgroundColor = [UIColor purpleColor];
        textView.frame = self.view.bounds;
//        textView.y = 64;
        textView.font = [UIFont systemFontOfSize:15];
//        NSLog(@"%zd",self.automaticallyAdjustsScrollViewInsets);
        self.textView = textView;//{64, 0, 0, 0}
    }
    
    return _textView;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    self.navigationItem.rightBarButtonItem.enabled = YES;

}


//添加输入控件

#pragma mark --初始化方法
//设置导航栏内容
- (void)setupNav{
    self.view.backgroundColor =[UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:0 target:self action:@selector(cancel)];
    self.view.backgroundColor =[UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:0 target:self action:@selector(send)];
    self.navigationItem.rightBarButtonItem.enabled = NO;

    NSString* name = [AccountTool account].name;
    NSString * prefix = @"发微博";
    
    if (name) {
        UILabel * titleView = [UILabel new];
        titleView.numberOfLines = 0;//自动换行
        titleView.y = 50;
        titleView.width = 200;
        titleView.height = 100;
        //    titleView.backgroundColor = [UIColor orangeColor];
        titleView.textAlignment = NSTextAlignmentCenter;
        
        NSString * str = [NSString stringWithFormat:@"%@\n%@",prefix,name];
        //创建一个带有属性的字符串 (颜色字体属性)
        NSMutableAttributedString* attrStr =  [[NSMutableAttributedString alloc]initWithString:str];
        //添加属性
        //    [attrStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:[str rangeOfString:prefix]];
        
        [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range: [str rangeOfString:name]];
        [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range: [str rangeOfString:name]];
        
        NSShadow * shadow = [[NSShadow alloc]init];
        shadow.shadowColor = [UIColor redColor];
        shadow.shadowBlurRadius = 10;
        shadow.shadowOffset = CGSizeMake(5, 5);
        //    [attrStr addAttribute:NSBackgroundColorAttributeName value:[UIColor purpleColor] range: [str rangeOfString:name]];
        
        
        //    NSTextAttachment * att = [[NSTextAttachment alloc]init];
        //    att.image = [UIImage imageNamed:@"vip"];
        //    NSAttributedString  * att2 =[NSAttributedString attributedStringWithAttachment:att];
        //    [attrStr appendAttributedString:att2];
        //    [attrStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"哈哈"]];
        
        titleView.attributedText = attrStr;
        self.navigationItem.titleView = titleView;
    }else{
        self.title = prefix;
    }
    
}


- (void)setupTextView{
    //在控制器中textViewcontentInset.top默认会等于64
    [self.view addSubview:self.textView];
    
    self.textView.alwaysBounceVertical = YES;//垂直方向上永远可以拖拽(弹簧效果)
    
//    UITextField *textField;
//    addtarget监听
//    [textField addTarget:self action:@selector(<#selector#>) forControlEvents:UIControlEventTouchUpInside];
//      通知监听
//    [[NSNotificationCenter defaultCenter]addObserver:self forKeyPath:nil options:UITextFieldTextDidEndEditingNotification context:nil];
    
//        [[NSNotificationCenter defaultCenter]addObserver:self forKeyPath:nil options:UITextViewTextDidEndEditingNotification context:nil];
    //文字改变监听通知
    [NoficationCenter addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self.textView];
    
    
    //键盘通知
//    UIKeyboardWillChangeFrameNotification 只要键盘frame(位置尺寸)将要发生改变时发出通知  基本覆盖了后面的所有情况 所以推荐用这个
//    UIKeyboardDidChangeFrameNotification;
//    键盘显示的时发出通知
//    UIKeyboardWillShowNotification
//        键盘隐藏时发出通知
//    UIKeyboardWillHideNotification;
//    UIKeyboardDidShowNotification
//    UIKeyboardDidHideNotification
    
    [NoficationCenter addObserver:self selector:@selector(KeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

    //表情选中的通知

    [NoficationCenter addObserver:self selector:@selector(EmotionDidSelect:) name:EmotionDidSelectNotification object:nil];
    
    
    //表情删除通知
    [NoficationCenter addObserver:self selector:@selector(EmotionDidDelete:) name:EmotionDidDeleteNotification object:nil];
    

    
    
  }

/*
        noti.userInfo = @{   The key for an NSValue object containing a CGRect NSValue 包装了一个CGRect
        //键盘弹出/隐藏后的frame
        UIKeyboardFrameEndUserInfoKey = NSRect: {{0, 227}, {320, 253}},
        //键盘弹出/隐藏后所耗费的时间
        UIKeyboardAnimationDurationUserInfoKey = 0.25,
        UIKeyboardIsLocalUserInfoKey = 1,
        //键盘弹出/隐藏动画的执行节奏(先快后慢,匀速) Curve 节奏
        UIKeyboardAnimationCurveUserInfoKey = 7
        }
 */

//键盘frame(位置尺寸)将要发生改变时发出通知
- (void)KeyboardWillChangeFrame:(NSNotification*)noti{
    NSLog(@"beginxxxxxxxx%f",self.toolBar.y);

    if (self.switchingKeyboard == YES) return;//如果在切换键盘 不更改
    NSLog(@"endxxxxxxxx%f",self.toolBar.y);

//    NSLog(@"KeyboardWillChangeFrame");
    NSDictionary * userInfo = noti.userInfo;
    NSTimeInterval interval = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];//动画持续时间
    [UIView animateWithDuration:interval animations:^{
       
        CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; //键盘frame
        self.toolBar.y = keyboardF.origin.y - self.toolBar.height;//键盘y去哪 toolbar.y 跟着变
        
        if (keyboardF.origin.y>=self.view.height) {//能来到这里说明就键盘的y 超过屏幕的高度 被遮盖了 让它显示出来
            self.toolBar.y = self.view.height - self.toolBar.height;
            }
        
//        NSLog(@"%@",NSStringFromCGRect(self.toolBar.frame));
        
        
        
    }];

}

#pragma mark --监听方法

//** 表情删除通知*/
- (void)EmotionDidDelete:(NSNotification*)notification{
    
    [self.textView deleteBackward];//从后往前删
    
}



- (void)EmotionDidSelect:(NSNotification*)notification{
  Emotion * emotion = notification.userInfo[SelectEmotionKey];
//    [self.textView insertText:emotion.chs];//insertText:从光标位置插入
   
    [self.textView insertEmotion:emotion];
    /**
     
     if (emotion.code) {
     [self.textView insertText:emotion.code.emoji];//insertText:从光标位置插入
     }else if(emotion.png){
     NSMutableAttributedString * attributedText =[[NSMutableAttributedString alloc]init];
     [attributedText appendAttributedString:self.textView.attributedText];//拼接之前的内容(图片,文字)
     UIImage * image= [UIImage imageNamed:emotion.png];//加载图片
     
     NSTextAttachment * attch = [[NSTextAttachment alloc]init];
     CGFloat attchWH = self.textView.font.lineHeight;
     attch.bounds = CGRectMake(0, -4, attchWH, attchWH);
     attch.image = image;
     NSAttributedString * imageStr =[NSAttributedString attributedStringWithAttachment:attch];//拼接图片字符串
     //        [attributedText appendAttributedString:imageStr];
     NSUInteger loc = self.textView.selectedRange.location;
     [attributedText insertAttributedString:imageStr atIndex:loc];
     //设置textView字体
     [attributedText addAttribute:NSFontAttributeName value:self.textView.font range:NSMakeRange(0, attributedText.length)];
     //        NSLog(@"%@",NSStringFromRange(self.textView.selectedRange));
     self.textView.attributedText = attributedText;
     self.textView.selectedRange = NSMakeRange(loc+1, 0);//之前选中的位置+1
     
     //        self.textView.font - > self.textView.text
     //        selectedRange : 控制textView文字选择范围 如果length ==0 selectedRange.location就是 TextView光标位置
     //        关于textView文字字体
     //        1.如果是普通文字 文字大小由textView.font控制
     //        2.如果是attributedText 文字大小由addAttribute设置字体
     }

     
     */
   //    NSLog(@"%@",emotion.chs);
}
/**
 *  监听文字改变
 */
- (void)textDidChange{
    
    self.navigationItem.rightBarButtonItem.enabled = self.textView.hasText;//有文字的时候能够点击
//    NSLog(@"xxxxxxxxx%zd",self.textView.hasText);

}



- (void)cancel{
    [self dismissViewControllerAnimated:YES completion:nil];
}


//https://api.weibo.com/2/statuses/update.json
//status 微博内容 string  true
//access_token   string  true
//pic 微博配图  binary 二进制数据 false
- (void)send{
    //判断发送哪种请求
    if (self.photosView.photos.count) {
        
        
        [self sendWithImage];//有图
    }else{
        
        [self sendWithoutImage];//无图

    }
    
    //dismiss
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


/**
 *  发布带有图片的微博
 */
- (void)sendWithImage{
    
    
    //1.请求管理者
    AFHTTPRequestOperationManager * manager= [AFHTTPRequestOperationManager manager];
    manager.responseSerializer =  [AFJSONResponseSerializer serializer];
    //2.拼接请求参数
    
    
    //3.发送请求
    //    https://api.weibo.com/oauth2/access_token?client_id=3920546846&client_secret=5cbe2134a99ad4bc4955f420d55ac7f5&grant_type=authorization_code&redirect_uri=http://pan.baidu.com/disk/home
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"status"]=self.textView.fullText;
    params[@"access_token"]=[AccountTool account].access_token;//包含用户帐号信息
    UIImage * image = [self.photosView.photos firstObject];
    NSLog(@"%@",self.photosView.photos);

    
    [manager POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //拼接图片数据 开放接口只支持一张图片
        NSData * data = UIImageJPEGRepresentation(image,1.0);;
        [formData appendPartWithFileData:data name:@"pic" fileName:@"1.jpg" mimeType:@"image/jpeg"];//pic参数名
        
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD showSuccess:@"发送成功"];
        NSLog(@"%@",responseObject);
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showSuccess:@"发送失败VI"];
        
        
    }];

    
}

/**
 *  发布纯文字微博
 */
- (void)sendWithoutImage{
    
    //1.请求管理者
    AFHTTPRequestOperationManager * manager= [AFHTTPRequestOperationManager manager];
    manager.responseSerializer =  [AFJSONResponseSerializer serializer];
    //2.拼接请求参数
    
    
    //3.发送请求
    //    https://api.weibo.com/oauth2/access_token?client_id=3920546846&client_secret=5cbe2134a99ad4bc4955f420d55ac7f5&grant_type=authorization_code&redirect_uri=http://pan.baidu.com/disk/home
    
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"status"]=self.textView.fullText;
    params[@"access_token"]=[AccountTool account].access_token;//包含用户帐号信息
    
        [manager POST:@"https://api.weibo.com/2/statuses/update.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary* responseObject) {//发布纯文字微博
    
            [MBProgressHUD showSuccess:@"发送成功"];
            NSLog(@"%@",responseObject);
    
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    
            [MBProgressHUD showSuccess:@"发送失败VI"];
        }];
    
    
    
}


#pragma mark --UITextViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self.view endEditing:YES];
    
}

@end
